package com.fxd.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxd.common.param.SkuReductionParam;
import com.fxd.common.param.SkuUpEsParam;
import com.fxd.common.vo.SkuHasStockVo;
import com.fxd.core.enums.SpuUpStatus;
import com.fxd.core.util.*;
import com.fxd.feigns.CouponFeign;
import com.fxd.feigns.EsFeign;
import com.fxd.feigns.WareFeign;
import com.fxd.model.coupon.SpuBoundsEntity;
import com.fxd.model.product.*;
import com.fxd.shopping.product.dao.SpuInfoDao;
import com.fxd.shopping.product.param.*;
import com.fxd.shopping.product.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeign couponFeign;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeign wareFeign;

    @Autowired
    EsFeign esFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //TODO 待完善分布式事务
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveParam param) {
        //保存spu基本信息：pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(param, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        //save后将id封装到bean对象里面
        this.saveBaseSpuInfo(spuInfoEntity);

        //保存spu的描述图片：pms_spu_info_desc
        List<String> decript = param.getDecript();
        if (CollectionUtils.isNotEmpty(decript)) {
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
            spuInfoDescEntity.setDecript(String.join(",", decript));
            spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        }

        //保存spu的图片集：pms_spu_images
        List<String> images = param.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //保存spu的规格参数：pms_product_attr_value
        List<BaseAttrs> baseAttrs = param.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((item) -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(item.getAttrValues());
            valueEntity.setQuickShow(item.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);

        //保存spu的积分信息：shopping_sms->sms_spu_bounds
        Bounds bounds = param.getBounds();
        SpuBoundsEntity spuBoundsEntity = new SpuBoundsEntity();
        BeanUtils.copyProperties(bounds, spuBoundsEntity);
        spuBoundsEntity.setSpuId(spuInfoEntity.getId());
        RR r = couponFeign.saveSpuBounds(spuBoundsEntity);
        if (r.getCode() != 0) {
            throw new ApiException("连接超时");
        }

        //保存当前spu对应的所有sku信息：
        //sku的基本信息：pms_sku_info
        List<Skus> skus = param.getSkus();
        if (CollectionUtils.isNotEmpty(skus)) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0l);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.savaSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    return StringUtils.isNotBlank(entity.getImgUrl());
                }).collect(Collectors.toList());

                //sku的图片信息：pms_sku_images
                skuImagesService.saveBatch(imagesEntities);

                //sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect1 = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect1);

                //sku的优惠，满减信息：shopping_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionParam skuReductionParam = new SkuReductionParam();
                BeanUtils.copyProperties(item, skuReductionParam);
                skuReductionParam.setSkuId(skuId);
                if (skuReductionParam.getFullCount() > 0 || skuReductionParam.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                    RR r2 = couponFeign.saveReduction(skuReductionParam);
                    if (r2.getCode() != 0) {
                        throw new ApiException("连接超时");
                    }
                }

            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = KeyUtils.getKey(params);
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = KeyUtils.get(params, "status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = KeyUtils.get(params, "brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = KeyUtils.get(params, "catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void spuUp(Long spuId) {
        // 组装需要的数据
        List<SkuUpEsParam> skuUpEsParams = new ArrayList<>();
        // 查出spuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // 查询当前spu的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.findSearchAttrsIds(attrIds);
        List<SkuUpEsParam.Attrs> realAttrs = baseAttrs.stream().filter(item -> searchAttrIds.contains(item.getAttrId()))
                .map(item -> {
                    SkuUpEsParam.Attrs curAttr = new SkuUpEsParam.Attrs();
                    BeanUtils.copyProperties(item, curAttr);
                    return curAttr;
                }).collect(Collectors.toList());

        //  库存服务查询是否有库存
        R<List<SkuHasStockVo>> skusHasStock = wareFeign.getSkusHasStock(skuIds);
        Map<Long, Boolean> stockMap = skusHasStock.getData().stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,
                SkuHasStockVo::getHasStock));
        if (CollectionUtils.isNotEmpty(skuInfoEntities)) {
            skuUpEsParams = skuInfoEntities.stream().map(skuInfo -> {
                SkuUpEsParam skuUpEsParam = new SkuUpEsParam();
                BeanUtils.copyProperties(skuInfo, skuUpEsParam);
                skuUpEsParam.setSkuPrice(skuInfo.getPrice());
                skuUpEsParam.setSkuImg(skuInfo.getSkuDefaultImg());
                // 库存服务查询是否有库存
                skuUpEsParam.setHasStock(stockMap == null ? false : stockMap.getOrDefault(skuUpEsParam.getSkuId(), false));
                // 刚上架，热度为0
                skuUpEsParam.setHotScore(0L);
                // 查询品牌和分类名称信息
                BrandEntity brand = brandService.getById(skuUpEsParam.getBrandId());
                skuUpEsParam.setBrandName(brand.getName());
                skuUpEsParam.setBrandImg(brand.getLogo());
                CategoryEntity category = categoryService.getById(skuUpEsParam.getCatalogId());
                skuUpEsParam.setCatalogName(category.getName());
                // 品牌规格查询
                skuUpEsParam.setAttrs(realAttrs);
                return skuUpEsParam;
            }).collect(Collectors.toList());
        }

        R<Boolean> r = esFeign.productStatusUp(skuUpEsParams);
        if (r.getData()) {
            log.info("商品上架成功");
            // 修改spu上架状态
            lambdaUpdate().eq(SpuInfoEntity::getId, spuId).set(SpuInfoEntity::getPublishStatus, SpuUpStatus.SPU_UP.getValue())
                    .set(SpuInfoEntity::getUpdateTime, new Date()).update();
        } else {
            log.info("商品上架失败");
            // TODO 重试？？？
        }

    }

}